package edu.mse.camel.client.session.views;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.events.EventIDs;
import edu.mse.camel.client.events.IEvent;
import edu.mse.camel.client.events.peer.ReceiveInvitationEvent;
import edu.mse.camel.client.events.peer.SendInvitationEvent;
import edu.mse.camel.client.events.server.AssignRoleEvent;
import edu.mse.camel.client.events.server.CreateSessionEvent;
import edu.mse.camel.client.events.server.JoinSessionEvent;
import edu.mse.camel.client.events.server.LeaveSessionEvent;
import edu.mse.camel.client.events.server.LoginEvent;
import edu.mse.camel.client.events.server.LogoutEvent;
import edu.mse.camel.client.session.plugin.Activator;
import edu.mse.camel.client.session.team.ITeamMember;
import edu.mse.camel.client.session.team.SESSION_CONSTANTS;
import edu.mse.camel.client.session.team.TEAMMEMBER_STATUS;
import edu.mse.camel.client.session.team.TeamList;
import edu.mse.camel.client.session.team.TeamVewConstants;
import edu.mse.camel.client.log.Debug;

public class SessionDialog {

	String userName;
	String password;

	String title;
	String description;
	Long sessionId;

	public void getIDandPassword() {

		boolean loginFlag = false;
		// String message = "";

		while (!loginFlag) {
			if (TeamList.getInstance().getMe() != null) {
				ErrorDialog ed = new ErrorDialog(new Shell(),
						DialogMessages.DIALOG_ERROR,
						DialogMessages.AlreadyLogin, new Status(IStatus.ERROR,
								Activator.PLUGIN_ID,
								DialogMessages.AlreadyLogin), IStatus.ERROR);
				ed.open();
				loginFlag = true;
			} else {
				Shell shell = new Shell();
				UsernamePasswordDialog getNamePwd = new UsernamePasswordDialog(
						shell);

				if (getNamePwd.open() == 0) {
					userName = getNamePwd.getUsername();
					password = getNamePwd.getPassword();

					if (userName.length() <= 0 || password.length() <= 0) {
						// Display error message
						ErrorDialog ed = new ErrorDialog(new Shell(),
								DialogMessages.DIALOG_ERROR,
								DialogMessages.InvalidLogin, new Status(
										IStatus.ERROR, Activator.PLUGIN_ID,
										DialogMessages.InvalidLogin),
								IStatus.ERROR);
						ed.open();
					} else {
						LoginEvent le = new LoginEvent(userName, password);
						EventManager.getInstance().dispatchEventSynchronous(le,
								true);

						if (le.isOpSuccessful()) {
							loginFlag = true;
							TeamList.getInstance().login(
									userName, null, TEAMMEMBER_STATUS.ONLINE, false);
							
							Debug.log_info(Activator.PLUGIN_ID, DialogMessages.SessionDialog_Login_Success);
						} else {

							Debug.log_info(Activator.PLUGIN_ID, DialogMessages.SessionDialog_Login_Fail);
							// Display error message
							ErrorDialog ed = new ErrorDialog(new Shell(),
									DialogMessages.DIALOG_ERROR,
									DialogMessages.InvalidLogin, new Status(
											IStatus.ERROR, Activator.PLUGIN_ID,
											DialogMessages.InvalidLogin),
									IStatus.ERROR);
							ed.open();
						}
					}
				} else {
					break;
				}
			}
		}

	}

	public String getUserName() {
		return this.userName;
	}

	public void displayMessage(String condition) {

		MessageBox messageBox = new MessageBox(new Shell(), SWT.OK | SWT.CANCEL);

		String message;
		if (condition.equals(SESSION_CONSTANTS.LOGOUT.toString())) {
			message = DialogMessages.SessionDialog_Message_Logout;
			messageBox.setText(DialogMessages.SessionDialog_Logout);
		} else if (condition.equals(SESSION_CONSTANTS.LEAVE.toString())) {
			message = DialogMessages.SessionDialog_Message_Leave;
			messageBox.setText(DialogMessages.SessionDialog_Leave);
		} else
			message = DialogMessages.SessionDialog_Message_Default;

		messageBox.setMessage(message);
		int response = messageBox.open();
		if (response == SWT.OK) {
			if (condition.equals(SESSION_CONSTANTS.LOGOUT.toString())) {
				LogoutEvent logoutEvent = new LogoutEvent();
				EventManager.getInstance().dispatchEventSynchronous(
						logoutEvent, true);
				if (logoutEvent.isOpSuccessful()) {
					TeamList.getInstance().logoutFromSession();
				}

			} else if (condition.equals(SESSION_CONSTANTS.LEAVE.toString())) {
				LeaveSessionEvent lse = new LeaveSessionEvent();
				EventManager.getInstance().dispatchEventSynchronous(lse, true);
				if (lse.isOpSuccessful()) {
					TeamList.getInstance().leaveSession();
				}
			}
		}
	}

	public void displayMessage(IEvent e) {

		MessageBox messageBox = new MessageBox(new Shell(), SWT.OK | SWT.CANCEL);

		String message = "";

		if (e.getEventID().equalsIgnoreCase(EventIDs.RECEIVE_INVITE_EVENT)) {
			ReceiveInvitationEvent rie = (ReceiveInvitationEvent) e;
			message = rie.getFacilitator()
					+ " wants to invite you to join session [";
			message += rie.getSessionTitle() + "]"
					+ System.getProperty("line.separator");
			message += "Description: ";
			message += rie.getSessionDesc()
					+ System.getProperty("line.separator");
			message += "Do you want to join? ";
			messageBox.setText("Receive Invitation");
		}

		messageBox.setMessage(message);

		int response = messageBox.open();
		if (response == SWT.OK) {
			if (e.getEventID().equalsIgnoreCase(EventIDs.RECEIVE_INVITE_EVENT)) {
				ReceiveInvitationEvent rie = (ReceiveInvitationEvent) e;
				joinSessionEvent(rie.getSessionId());
			}
		}
	}

	public void displayFacilitatorMessage(IEvent e) {

		MessageBox messageBox = new MessageBox(new Shell(), SWT.OK);

		String message = "";

		if (e.getEventID().equalsIgnoreCase(
				EventIDs.NOTIFY_SESSION_ROLE_CHANGE_EVENT)) {
			message = "You have been invited as the facilitator for this session";
			messageBox.setText("Receive Facilitator Invitation");
		}
		messageBox.setMessage(message);
		messageBox.open();

	}

	public void setTitleAndDesc() {

		Shell shell = new Shell();

		boolean isSessionCreated = false;
		CreateSessionDialog setTitleDesc = null;

		while (!isSessionCreated) {
			setTitleDesc = new CreateSessionDialog(shell);

			// setTitleDesc.open();

			if (setTitleDesc.open() == 0) {
				title = setTitleDesc.getSessionName();
				description = setTitleDesc.getSessionDesc();
				if (title.length() <= 0) {
					ErrorDialog ed = new ErrorDialog(new Shell(),
							DialogMessages.DIALOG_ERROR,
							DialogMessages.CreateSession_ErrorMessage,
							new Status(IStatus.ERROR, Activator.PLUGIN_ID,
									DialogMessages.CreateSession_ErrorMessage),
							IStatus.ERROR);
					ed.open();
				} else {
					isSessionCreated = true;
					break;
				}
			} else {
				break;
			}
		}

		if (title.length() > 0) {
			setView();
			CreateSessionEvent cse = new CreateSessionEvent(title, description);
			EventManager.getInstance().dispatchEventSynchronous(cse, true);

			if (cse.isOpSuccessful()) {
				TeamList.getInstance().createSession();	
			} else {
				// error message
			}
		}
	}

	public void joinSession() {

		Shell shell = new Shell();
		JoinSessionDialog selectSession = new JoinSessionDialog(shell);

		selectSession.open();
		title = selectSession.getSessionName();

		if (title.length() > 0) {

			joinSessionEvent(getSessionID(title));
			Debug.log_info(Activator.PLUGIN_ID, DialogMessages.SessionDialog_Event_Dispatch_Join_Session);

		}
	}

	private Long getSessionID(String sessionInfo) {
		return Long.valueOf(sessionInfo.substring(0, sessionInfo
				.indexOf(TeamVewConstants.SESSION_ID_TITLE_SEPARATOR)));
	}

	public void joinSessionEvent(Long sessionId) {
		setView();
		JoinSessionEvent jse = new JoinSessionEvent(sessionId);
		EventManager.getInstance().dispatchEventSynchronous(jse, true);
		if (jse.isOpSuccessful()) {
			TeamList.getInstance().joinSession(sessionId);
		} else
			{		
				ErrorDialog ed = new ErrorDialog(new Shell(),
					DialogMessages.DIALOG_ERROR,
					DialogMessages.Session_Already_Close,
					new Status(IStatus.ERROR, Activator.PLUGIN_ID,
							DialogMessages.Session_Already_Close),
					IStatus.ERROR);
				ed.open();			
		}
	}

	private void setView() {
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		IViewPart view = page.findView("edu.mse.camel.client.playback.views.PlaybackView");
		if(view != null)
			page.hideView(view);
		try {
			page.showView("edu.mse.camel.client.chat.views.ChatView");
		} catch (PartInitException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void inviteMember(ITeamMember inviteTeamMember) {

		SendInvitationEvent sie = new SendInvitationEvent();
		sie.setInvitee(inviteTeamMember.getName());
		EventManager.getInstance().dispatchEventSynchronous(sie, true);

	}

	public void setFacilitator(ITeamMember selectedTeamMember) {

		String nameOfNewFacilitator = selectedTeamMember.getName();
		AssignRoleEvent are = new AssignRoleEvent(nameOfNewFacilitator,
				ITeamMember.FACILITATOR);
		EventManager.getInstance().dispatchEventSynchronous(are, true);
		Debug.log_info(Activator.PLUGIN_ID, DialogMessages.SessionDialog_Assign_Role_Event);

		if (are.isOpSuccessful()) {
			TeamList.getInstance().makeFacilitator(nameOfNewFacilitator, true);
		}

	}
}
